package com.jinkeen.xiaxie.util

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.BatteryManager
import android.os.Build
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import androidx.annotation.RequiresApi
import com.jinkeen.xiaxie.R
import com.jinkeen.xiaxie.base.MyApplication
import com.landicorp.android.eptapi.tms.TermInfo
import com.landicorp.android.eptapi.utils.SystemInfomation
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.NetworkInterface
import java.text.SimpleDateFormat
import java.util.*

/**
 * @description: 获取系统信息
 * @author whz
 * @date 2021/11/18 11:03
 * @version 1.0
 */
@SuppressLint("MissingPermission", "HardwareIds")
class SystemInfo(context: Context) {
    private var termInfo: TermInfo = TermInfo()
    private var telephonyMgr: TelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    var deviceInfo: SystemInfomation.DeviceInfo = SystemInfomation.getDeviceInfo()
    var context: Context? = context

    /**
     * 获取当前开发状态
     * DEVELOP_STATE_UNKNOWN - 未知态
     * DEVELOP_STATE_PRODUCE - 生产态
     * DEVELOP_STATE_NORMAL - 使用态
     * DEVELOP_STATE_MAINTAIN - 维修态
     * DEVELOP_STATE_MOCKUP - 调试态
     */
    fun getDevelopState(): Int = SystemInfomation.getDevelopState()

    //获取系统版本号
    fun getSystemVersion(): String = SystemInfomation.getSystemVersion()

    //获取系统内核版本号
    fun getAndroidkernelversion(): String = readLine("/proc/version")

    //获取IMSI
    fun getIMSI(): String = telephonyMgr.subscriberId

    //获取imei
    fun getIMEI(): String = telephonyMgr.getDeviceId()

    //获取ICCID
    fun getICCID(): String = telephonyMgr.simSerialNumber

    //获取厂商标识
    fun getEquipmentManufacturers(): String = termInfo.equipmentManufacturers

    //获取终单类型
    fun getTerminalType(): String = termInfo.terminalType

    //获取固件版本号
    fun getFirmwareVersion(): String = termInfo.platform

    //获取PsamId
    fun getPsamId(): String = deviceInfo.specialPSamId

    //更新系统当前时间
    @SuppressLint("SimpleDateFormat")
    fun updateSystemDateTime(datatime: String): Boolean {
        val date: Date = SimpleDateFormat("yyyyMMddHHmmss").parse(datatime)
        return SystemInfomation.setCurrentDateTime(date)
    }

    //获取硬件序列号
    fun getHardwareSN(): String = deviceInfo.hardWareSn

    //获取序列号
    fun getSeriaNo(): String = deviceInfo.serialNo

    //获取硬件版本号
    fun getHardwareVersion(): String = getSystemVersion()

    //获取rom版本号
    fun getRomVersion(): String = getSystemVersion()

    fun readLine(filePath: String): String {
        var reader: BufferedReader? = null
        try {
            reader = BufferedReader(FileReader(filePath))
            val line = reader.readLine()
            return if (line == null) "" else line
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (reader != null) {
                try {
                    reader.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return ""
    }

    /**
     * 获取电池信息
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun getBatterInfo(): Int {
        val manager = context!!.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
        return manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
    }


    //获取电池信息
    fun monitorBatteryState() {
        val batteryLevelRcvr = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                //电池剩余容量
                val level = intent?.getIntExtra("level", 0)
                //电池总容量
                val scale = intent?.getIntExtra("scale", 100)
                val status = intent?.getIntExtra("status", -1)
                val health = intent?.getIntExtra("health", -1)

            }

        }
    }

    val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
    val battery = context!!.registerReceiver(null, intentFilter)

    //电池信息
    fun deviceChargingStatus(): String {

        when (battery?.getIntExtra(BatteryManager.EXTRA_STATUS, -1)) {
            BatteryManager.BATTERY_STATUS_CHARGING -> return MyApplication.instance!!.getString(
                R.string.isCharging
            )
            BatteryManager.BATTERY_STATUS_FULL -> return MyApplication.instance!!.getString(
                R.string.fullCharging
            )
            BatteryManager.BATTERY_STATUS_DISCHARGING -> return MyApplication.instance!!.getString(
                R.string.disCharging
            )
            BatteryManager.BATTERY_STATUS_NOT_CHARGING -> return MyApplication.instance!!.getString(
                R.string.noCharging
            )
            BatteryManager.BATTERY_STATUS_UNKNOWN -> return MyApplication.instance!!.getString(
                R.string.unKnown
            )
            else -> return MyApplication.instance!!.getString(R.string.unKnown)
        }
    }

    fun deviceBattryPer(): String {
        val level = battery?.getIntExtra(BatteryManager.EXTRA_LEVEL, 1)
        val scale = battery?.getIntExtra(BatteryManager.EXTRA_SCALE, 1)
        if (level != null) {
            return "${level * 100 / scale!!}%"
        }
        return "100%"
    }

    //cpu频率
    fun getCpu(): Long {
        var result = 0L
        try {
            var line: String
            val br =
                BufferedReader(FileReader("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"))
            if (br.readLine().also { line = it } != null) {
                result = line.toLong()
            }
            br.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result
    }

    /** get CPU rate
     * @return
     */
    fun getProcessCpuRate(): Int {
        val tv = StringBuilder()
        var rate = 0
        try {
            var Result: String
            val p: Process = Runtime.getRuntime().exec("top -n 1")
            val br = BufferedReader(InputStreamReader(p.inputStream))
            while (br.readLine().also { Result = it } != null) {
                if (Result.trim { it <= ' ' }.isEmpty()) {
                    continue
                } else {
                    val CPUusr = Result.split("%").toTypedArray()
                    tv.append(
                        """
                        USER:${CPUusr[0]}
                        
                        """.trimIndent()
                    )
                    val CPUusage = CPUusr[0].split("User").toTypedArray()
                    val SYSusage = CPUusr[1].split("System").toTypedArray()
                    tv.append("""CPU:${CPUusage[1].trim { it <= ' ' }} length:${CPUusage[1].trim { it <= ' ' }.length}
"""
                    )
                    tv.append("""SYS:${SYSusage[1].trim { it <= ' ' }} length:${SYSusage[1].trim { it <= ' ' }.length}
"""
                    )
                    rate = CPUusage[1].trim { it <= ' ' }.toInt() + SYSusage[1].trim { it <= ' ' }
                        .toInt()
                    break
                }
            }
        } catch (e: IOException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }
        println(rate.toString() + "")
        return rate
    }

    private val cm: ConnectivityManager =
        context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    private val activeNetwork = cm.activeNetworkInfo

    //获取网络类型
    fun getNetworkType(): String = activeNetwork!!.typeName

    //是否使用无线网络
    fun isUseWFI(): String {
        return if (activeNetwork!!.type == ConnectivityManager.TYPE_WIFI) {
            "是"
        } else {
            "否"
        }
    }

    //是否使用3g网络
    fun isUse3G(): String {
        return if (activeNetwork!!.type == ConnectivityManager.TYPE_MOBILE) {
            "是"
        } else {
            "否"
        }
    }


    fun getNetworkIp(): String {
        val en = NetworkInterface.getNetworkInterfaces()
        val intf = en.nextElement()
        return intf.interfaceAddresses[0].address.toString()
    }

    //获取手机信号信息
    fun getTeleInfo():String {
        val tel = context!!.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        var strength=""
        tel.listen(object : PhoneStateListener() {
            override fun onSignalStrengthsChanged(signalStrength: SignalStrength?) {
                super.onSignalStrengthsChanged(signalStrength)
                strength= signalStrength!!.cdmaDbm.toString()
            }
        }, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS or PhoneStateListener.LISTEN_SERVICE_STATE)
        return strength
    }

}